package cn.itcast.chapter05.session.example02;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @Author: 18148
 * @Date: 2020-06-05 16:37:05
 */
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String checkCode = req.getParameter("check_code");
        String saveCode= (String) req.getSession().getAttribute("check_code");
        PrintWriter pw = resp.getWriter();
        if(("itcast").equals(username)&&("123").equals(password)){
            User user = new User();
            user.setUsername(username);
            user.setPassword(password);
            req.getSession().setAttribute("user",user);
            resp.sendRedirect("/web/indexServlet");
        }else if(checkCode.equals(saveCode)){
            pw.write("用户名或密码错误，登录失败");
        }else {
            pw.write("验证码错误");
        }
    }
}
